package com.originskyseed.platform.log.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.mongodb.api.MongoUtil;
import com.originskyseed.platform.core.tenant.util.TenantCodeUtil;
import com.originskyseed.platform.core.util.bean.PrimaryKeyGeneratorUtil;
import com.originskyseed.platform.log.model.InterfaceSynchroLog;
import com.originskyseed.platform.log.service.IInterfaceSynchroLogService;

/**
 * Service接口实现类（OSI_INTERFACE_SYNCHRO_LOG）
 *
 * @author ling
 */
@DubboService
@Component("interFaceSynchroLogService")
public class InterfaceSynchroLogServiceImpl implements IInterfaceSynchroLogService {

	/**
	 * 日志记录表
	 */
	private final static String INTERFACE_SYNCHRO_LOG = "osi_interface_synchro_log";

	/**
	 * 插入记录（仅非空值字段）
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int insertSelective(InterfaceSynchroLog record) throws Exception {
		String id = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
		JSONObject jsonObject = new JSONObject();
		// 设置mongodb数据
		jsonObject.put("id", id);
		jsonObject.put("state", record.getState());
		jsonObject.put("startTime", record.getStartTime());
		jsonObject.put("endTime", record.getEndTime());
		jsonObject.put("errorLog", record.getErrorLog());
		jsonObject.put("desc", record.getDesc());
		jsonObject.put("name", record.getName());
		jsonObject.put("type", record.getType());
		jsonObject.put("createTime", new Date());
		MongoUtil.getInstance().insert(jsonObject, INTERFACE_SYNCHRO_LOG);
		return 1;
	}

	/**
	 * 插入记录（仅非空值字段）
	 *
	 * @param InterfaceSynchroLogLsit
	 * @return
	 * @throws Exception
	 */
	@Override
	public int batchInsertByList(List<InterfaceSynchroLog> InterfaceSynchroLogLsit) throws Exception {
		for (InterfaceSynchroLog InterfaceSynchroLog : InterfaceSynchroLogLsit) {
			InterfaceSynchroLog.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
			InterfaceSynchroLog.setCreateTime(new Date());
		}
		MongoUtil.getInstance().batchInsertByList(InterfaceSynchroLogLsit, INTERFACE_SYNCHRO_LOG);
		return 1;
	}

	/**
	 * 查询记录
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public InterfaceSynchroLog selectByPrimaryKey(String id) throws Exception {
		Query query = getQuery(new HashMap() {
			{
				this.put("id", id);
			}
		});
		List<InterfaceSynchroLog> list = MongoUtil.getInstance().selectListByQuery(query, InterfaceSynchroLog.class, INTERFACE_SYNCHRO_LOG);
		if (list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	/**
	 * 查询列表
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<InterfaceSynchroLog> selectList(InterfaceSynchroLog record) throws Exception {
		Query query = getQuery(record.toMap());
		List<JSONObject> jsonObjectList = MongoUtil.getInstance().selectListByQuery(query, JSONObject.class, INTERFACE_SYNCHRO_LOG);
		return getInterfaceSynchroLogJSON(jsonObjectList);
	}

	/**
	 * 分页查询列表
	 *
	 * @param params
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<InterfaceSynchroLog> selectListByPage(Map<String, Object> params, BasePage<InterfaceSynchroLog> page) throws Exception {
		Query query = getQuery(params);
		query.with(Sort.by(new Sort.Order(Sort.Direction.DESC, "createTime")));
		List<InterfaceSynchroLog> jsonObjectList = MongoUtil.getInstance().selectListByPage(query, page, InterfaceSynchroLog.class, INTERFACE_SYNCHRO_LOG);
		// 获取总数
		Long totalNum = MongoUtil.getInstance().selectCountByQuery(query, INTERFACE_SYNCHRO_LOG);
		page.setTotalRecord(Integer.valueOf(String.valueOf(totalNum)));
		page.setResults(jsonObjectList);
		return page;
	}

	@Override
	public Boolean deleteInterfaceSynchroLog(String day, String tenantCode) throws Exception {
		if (StringUtils.isNotEmpty(tenantCode)) {
			TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		// 获取60天之前的日期
		Date orderDays = DateUtils.addDays(date, -Integer.valueOf(day));
		String createTime = dateFormat.format(orderDays);
		Query query = getQuery(new HashMap() {
			{
				this.put("startTimeEnd", createTime);
			}
		});
		MongoUtil.getInstance().deleteByQuery(query, INTERFACE_SYNCHRO_LOG);
		return true;
	}

	/**
	 * 公共查询条件
	 *
	 * @param params
	 * @return
	 * @throws ParseException
	 */
	private Query getQuery(Map<String, Object> params) throws ParseException {
		Query query = new Query();
		Criteria criteria = new Criteria();
		if (ObjectUtils.allNotNull(params.get("startTime")) && ObjectUtils.allNotNull(params.get("endTime"))) {
			Calendar cld = getCalendar((String) params.get("endTime"));
			criteria.andOperator(Criteria.where("createTime").gte(DateUtils.parseDate((String) params.get("startTime"), "yyyy-MM-dd")), Criteria.where("createTime").lte(cld.getTime()));
			params.put("startTime", null);
			params.put("endTime", null);
		}
		if (params.get("id") != null) {
			criteria.and("id").is(String.valueOf(params.get("id")));
		}
		if (params.get("state") != null) {
			criteria.and("state").is(Integer.valueOf(String.valueOf(params.get("state"))));
		}
		if (params.get("startTime") != null) {
			try {
				criteria.and("createTime").gte(DateUtils.parseDate((String) params.get("startTime"), "yyyy-MM-dd"));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if (params.get("endTime") != null) {
			Calendar cld = getCalendar((String) params.get("endTime"));
			criteria.and("createTime").lte(cld.getTime());
		}
		if (params.get("errorLog") != null) {
			criteria.and("errorLog").is(String.valueOf(params.get("errorLog")));
		}
		if (params.get("desc") != null) {
			criteria.and("desc").is(String.valueOf(params.get("desc")));
		}
		if (params.get("name") != null) {
			criteria.and("name").is(String.valueOf(params.get("name")));
		}
		if (params.get("type") != null) {
			criteria.and("type").is(Integer.valueOf(String.valueOf(params.get("type"))));
		}

		query.addCriteria(criteria);
		return query;
	}

	private List<InterfaceSynchroLog> getInterfaceSynchroLogJSON(List<JSONObject> list) {
		List<InterfaceSynchroLog> InterfaceSynchroLogList = new ArrayList<>();
		for (JSONObject jsonObject : list) {
			// JSONObject timeObject = JSONObject.parseObject((JSONObject.toJSONString(jsonObject.get("createTime"))));
			// jsonObject.put("createTime", timeObject.get("$numberLong"));
			InterfaceSynchroLog InterfaceSynchroLog = JSONObject.parseObject(JSON.toJSONString(jsonObject), InterfaceSynchroLog.class);
			InterfaceSynchroLogList.add(InterfaceSynchroLog);
		}
		return InterfaceSynchroLogList;
	}

	/**
	 * 获取加一天的时间
	 *
	 * @param
	 * @return
	 */
	private Calendar getCalendar(String value) {
		Date endTime = null;
		try {
			endTime = DateUtils.parseDate(value, "yyyy-MM-dd");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar cld = Calendar.getInstance();
		cld.setTime(endTime);
		cld.add(Calendar.DATE, 1);
		return cld;
	}
}
